
'''The implementation of PlurkAPI using urllib2'''

import plurk_api  # inheritance
import cookielib
import urllib
import urllib2

class PlurkAPI(plurk_api.PlurkAPI):
  '''An HTTP/HTTPS layer based on urllib2'''

  class HttpErrorHandler(urllib2.BaseHandler):
    '''Error handler class for http protocol used in PlurkConnection'''
    def __init__(self):
      self.status_code = 0
      self.response_body = ''
    def http_error_400(self, req, fp, code, msg, hdrs):
      self.status_code = code
      self.response_body = fp.read()

  def __init__(self, api_key, api_url='http://www.plurk.com/API',
               debug_level=0):
    plurk_api.PlurkAPI.__init__(self, api_key, api_url, debug_level)
    self.body = None
    self._http_error_handler = self.HttpErrorHandler()
    self._cookies = cookielib.CookieJar()
    hh = urllib2.HTTPHandler()
    hhs = urllib2.HTTPSHandler()
    hh.set_http_debuglevel(debug_level)
    hhs.set_http_debuglevel(debug_level)
    self._opener = urllib2.build_opener(hh, hhs,
        self._http_error_handler,
        urllib2.HTTPCookieProcessor(self._cookies))

  def _Connect(self, url, **kw):
    self._body = ''
    try:
      self._fp = self._opener.open(url, urllib.urlencode(kw))
      self._body = self._fp.read()
      self._status_code = 200
      self._error = ''
    except urllib2.HTTPError, v:
      self._status_code = v.code
      self._error = v.msg
      self._body = self._http_error_handler.response_body
    except urllib2.URLError, v:
      self._status_code = -1
      self._error = v.reason
      self._body = self._http_error_handler.response_body

  def GetCookies(self):
    return self._cookies

  def GetBody(self):
    return self._body

  def GetStatusCode(self):
    return self._status_code

  def GetErrorMessage(self):
    return self._error
